package bean;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import toolkit.Debug;
import form.Form;

abstract public class AbstractBean extends HashMap<String, Object>
{
	private static final long serialVersionUID = 1L;
	
	// Cache the class name, otherwise we need to make those function calls multiple times.
	private String className = this.getClass().getName();
	
	@Override
	public Object get(Object key)
	{
		Debug.log(className + ".get(" + key + ")");
		
		return super.get(key);
	}

	@Override
	public Object put(String key, Object value)
	{
		Debug.log(className + ".put(" + key + ", " + value + ")");
		
		return super.put(key, value);
	}
	
	@SuppressWarnings("unchecked")
	public void populate(HttpServletRequest request)
	{
		Debug.log(className + ".populate()");
		
		Enumeration<String> names = request.getParameterNames();
		
		if (names != null)
		{
			while (names.hasMoreElements())
			{
				String name = names.nextElement();
				Object value = request.getParameter(name);
				
				put(name, value);
			}
		}
		
		Debug.log(className + ".populate(): " + this);
	}

	public void populate(Form form)
	{
		populate(form.getValues());
	}
	
	public void populate(Map<String, Object> values)
	{
		for (String key: values.keySet())
		{
			put(key, values.get(key));
		}
	}
	
	/*public boolean validate(String[] keys)
	{
		Debug.log(className + ".validate(" + keys + ")");
		
		for (String key: keys)
		{
			Object value = get(key);
			
			if (value == null)
			{
				return false;
			}
			else if (value instanceof String && ((String) value).isEmpty())
			{
				return false;
			}
		}
		
		return true;
	}
	
	public String required(String[] keys)
	{
		String code = "";
		
		for (String key: keys)
		{
			Object value = get(key);
			
			if (value instanceof String && ((String) value).isEmpty())
			{
				code += ("<br />" + key + " is a required field.");
			}
		}
		
		return code;
	}*/
	
	@Override
	public void finalize() throws Throwable
	{
		Debug.log(className + ".finalize()");

		super.finalize();
	}
}
